package Panel;


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Path;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import learn.Files;

public class FilesPanel implements ActionListener {

	JPanel opcje = new JPanel();
	JTextArea text = new JTextArea();
	JScrollPane scroll = new JScrollPane(text);
	JButton buttonSave = new JButton("Zapisz");
	JButton buttonLoad = new JButton("Wczytaj");

	String url;
	
	public FilesPanel(JPanel content){
		
		content.removeAll();
		scroll.setPreferredSize(new Dimension(600,400));
		scroll.setBackground(Color.WHITE);
		
		buttonLoad.setActionCommand("load");
		buttonLoad.addActionListener(this);
		buttonSave.setActionCommand("save");
		buttonSave.addActionListener(this);		
		
		opcje.setLayout( new GridLayout(1,2) );
		opcje.add(buttonSave);
		opcje.add(buttonLoad);

		content.setLayout( new BorderLayout() );
		content.add(scroll, BorderLayout.CENTER);
		content.add(opcje, BorderLayout.SOUTH);
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		switch (e.getActionCommand()) {
		case "load":
			JFileChooser fileChooser = new JFileChooser();
			if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
				try {
					url = fileChooser.getSelectedFile().getAbsolutePath();
					BufferedReader bufferedReader = new BufferedReader(new FileReader(fileChooser.getSelectedFile()));
					String line;
					while ( (line = bufferedReader.readLine()) != null )
						text.append(line+"\r\n");
					bufferedReader.close();
				} catch (IOException ex) {
					ex.printStackTrace();
				}
			}
			break;
		case "save":
	        BufferedWriter bufferedWriter = null;
	        try {
	        	bufferedWriter = new BufferedWriter(new FileWriter(url));
	            bufferedWriter.write(text.getText());
	        } catch (FileNotFoundException ex) {
	        	ex.printStackTrace();
	        } catch (IOException ex) {
	        	ex.printStackTrace();
	        } finally {
	        	try {
		        	if (bufferedWriter != null) {
		        		bufferedWriter.flush();
		        		bufferedWriter.close();
		        	}
	        	} catch (IOException ex) {
	        		ex.printStackTrace();
	        	}
	        }
			break;
		}
	}

}
